import { PayloadAction, createSlice } from '@reduxjs/toolkit';
import { ToolkitStore } from '@reduxjs/toolkit/dist/configureStore';
import { AppStore } from '../types';
import main, { AppLocalKey } from '../main';

import { startUp } from './startupReducer';
import { apiLogout } from '@src/page/loginPage/api';

const logoutSlice = createSlice({
  name: 'logout',
  initialState: undefined,
  reducers: {
    logoutRequest: (state: undefined) => {
      return state;
    },
  },
});

export const { logoutRequest } = logoutSlice.actions;
export default logoutSlice.reducer;

export const logoutEffect = {
  'logout/logoutRequest': async (store: ToolkitStore<AppStore>, action: PayloadAction<{ callback?: Function }>) => {
    try {
      await apiLogout();
    } catch (e: any) {}
    main.user = undefined;
    main.permissions = undefined;
    main.roles = undefined;
    main.loginKey = undefined;
    delete main.api.defaults.headers.common['Authorization'];
    localStorage.removeItem(AppLocalKey.loginToken);
    store.dispatch(startUp('start'));
  },
};
